package test;

public class Transform {

    private static final double PI = Math.PI;
    private static final double mercatorMax = 20037508.34;

    /**
     * 4326坐标转3857即经纬度转墨卡托
     * @param lon
     * @param lat
     */
    public static void transformTo3857(double lon,double lat){
        double mercatorx = lon * mercatorMax / 180;
        double mercatory = Math.log(Math.tan(((90+lat) * PI) / 360)) / (PI / 180);
        mercatory = mercatory * mercatory / 180;
        System.out.printf("经纬度坐标转墨卡托后的坐标:%f,%f",mercatorx,mercatory);
        System.out.println("----");
    }

    /**
     * 墨卡托坐标转3857即墨卡托转经纬度
     * @param mercatorx
     * @param mercatory
     */
    public static void tarnsformTo4326(double mercatorx,double mercatory){
        double lon = mercatorx/mercatorMax * 180;
        double lat = mercatory/mercatorMax * 180;
        lat = (180 / PI) * (2 *Math.atan(Math.exp((lat * PI) / 180)) - PI / 2);
        System.out.printf("墨卡托坐标转经纬度后的坐标:%f,%f \n",lon,lat);
        System.out.println("----");
    }

    public static double[] mercator2LngLat(double mercatorX, double mercatorY) {
        double[] xy = new double[2];
        double x = mercatorX / 20037508.34 * 180;
        double y = mercatorY / 20037508.34 * 180;
        y = 180 / PI * (2 * Math.atan(Math.exp(y * PI / 180)) - PI / 2);
        xy[0] = x;
        xy[1] = y;
        System.out.println(xy[0]+","+xy[1]);
        return xy;
    }

    public static void main(String[] args) {
        tarnsformTo4326(13135699.911778,6.349291);
        mercator2LngLat(13135699.911778,6.349291);
        transformTo3857(118.000000,32.000000);
        transformTo3857(118.000000000002,5.7036651499916665E-5);
    }

}